package com.web22_2_1.filter;

import java.io.IOException;

import com.web22_2_1.utils.JwtUtil;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

@WebFilter(urlPatterns={"/*"})
public class LoginFilter extends HttpFilter {
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse resp = (HttpServletResponse) response;

		// 添加CORS头部，以应对响应跨域问题
		resp.setHeader("Access-Control-Allow-Origin", req.getHeader("Origin"));
		resp.setHeader("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS");
		resp.setHeader("Access-Control-Allow-Headers", "Authorization, Content-Type");
		resp.setHeader("Access-Control-Allow-Credentials", "true");

		// 处理预检请求
		if ("OPTIONS".equalsIgnoreCase(req.getMethod())) {
			resp.setStatus(HttpServletResponse.SC_OK);
			return;
		}

		// 1. 获取请求url
		String url = req.getRequestURL().toString();
		System.out.println("拦截到请求,请求路径为：" + url);

		// 2. 判断请求url是否为登录url, 放行
		if (url.endsWith("/login.jsp") || url.endsWith("/LoginServlet")) {
			System.out.println("放行请求：" + url);
			chain.doFilter(request, response);
			return;
		}

		// 3. 获取请求头中的JWT令牌(规定为Authorization)
		HttpSession session = req.getSession();
		String jwt = (String) session.getAttribute("token");

		// 4. 判断令牌是否存在, 如果不存在，返回错误结果
		if (jwt == null) {
			System.err.println("令牌不存在");
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}

		// 5. 解析令牌，如果解析失败，返回错误结果(未登录)
		try {
			JwtUtil.parseJWT(jwt);
		} catch (Exception e) {
			System.err.println("JWT解析失败");
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
			return;
		}

		// 6. 放行
		System.out.println("放行请求：" + url);
		chain.doFilter(request, response);
	}

}
